from django.contrib.auth import get_user_model
from django.utils.deprecation import MiddlewareMixin
from django.contrib.auth.models import AnonymousUser

User = get_user_model()

class UserAuthMiddleware(MiddlewareMixin):
    """
    用户认证中间件
    从请求头中获取用户信息并设置到request.user
    """
    
    def process_request(self, request):
        # 从请求头获取用户ID
        user_id = request.headers.get('X-USER-ID')
        if user_id:
            try:
                user_id = int(user_id)
                user = User.objects.get(id=user_id)
                # 设置用户为已认证状态
                user.backend = 'django.contrib.auth.backends.ModelBackend'
                request.user = user
                return None
            except (ValueError, TypeError, User.DoesNotExist):
                pass
        
        # 从Authorization头获取token
        auth_header = request.headers.get('Authorization', '')
        if auth_header.startswith('Bearer '):
            token = auth_header[7:]  # 去掉 'Bearer ' 前缀
            if token.startswith('user_'):
                try:
                    user_id = int(token[5:])  # 去掉 'user_' 前缀
                    user = User.objects.get(id=user_id)
                    # 设置用户为已认证状态
                    user.backend = 'django.contrib.auth.backends.ModelBackend'
                    request.user = user
                    return None
                except (ValueError, TypeError, User.DoesNotExist):
                    pass
        
        # 如果都没有找到用户，保持原有的用户状态
        return None
